package com.mylib.libcore.dialog;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.mylib.libcore.R;
import com.mylib.libcore.bean.AppOpenBean;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;

import java.io.File;
import java.util.List;


/**
 * 升级弹框
 */
public class VersionUpDialog extends PopupWindow {

    private TextView tv_content,tv_version_number,tv_btn;
    private ProgressBar progressBar;
    private Context mCntext;
    private View mMenuView;
    public DialogViewClink dialogViewClink;
    private String packageName = "com.wandian";
    private String apkPath="";
    private String apkName = "wandian";
    private String fileLoad = "download/";
    private String apkFilePath = "";
    private AppOpenBean appOpenBean;
    public interface  DialogViewClink{
        void viewClink(boolean isSign);
    }

    public VersionUpDialog(Context context, AppOpenBean appOpenBean, DialogViewClink dialogViewClink) {
        super(context);
        this.mCntext = context;
        this.appOpenBean = appOpenBean;
        this.dialogViewClink =dialogViewClink;
        packageName = context.getPackageName();
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.dialog_version_up, null);
        tv_content = (TextView) mMenuView.findViewById(R.id.tv_version_content);
        tv_version_number = (TextView) mMenuView.findViewById(R.id.tv_version_number);
        tv_btn = (TextView) mMenuView.findViewById(R.id.tv_version_btn);
        progressBar = (ProgressBar) mMenuView.findViewById(R.id.tv_version_progressbar);

       if(UIUtils.isEmpty(appOpenBean)){
           dismiss();
       }
        tv_version_number.setText("V"+ appOpenBean.getvName()+"更新内容：");
       if(!UIUtils.isEmpty(appOpenBean.getContent())){
           String[] contentList = appOpenBean.getContent().split("#");
           String contentText="";
           if(!UIUtils.isEmpty(contentList)){
               for(String text:contentList){
                   contentText =contentText+text+"\n";
               }
           }
           tv_content.setText(contentText+"");
       }

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            this.setClippingEnabled(false);
        }

        //设置SelectPicPopupWindow的View
        this.setContentView(mMenuView);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(LayoutParams.MATCH_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(LayoutParams.MATCH_PARENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
//        //设置SelectPicPopupWindow弹出窗体动画效果
//        this.setAnimationStyle(R.style.popwin_anim_style);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x10000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);

        tv_btn.setOnClickListener(v -> {
            if(UIUtils.isFastClick()) return;
            if(tv_btn.getText().toString().equals("立即更新") || tv_btn.getText().toString().equals("文件异常，重新下载")){
                initPermissions();
            }

        });
    }

    @Override
    public void showAsDropDown(View anchor) {
        if(Build.VERSION.SDK_INT >= 24) {
            Rect rect = new Rect();
            anchor.getGlobalVisibleRect(rect);
            int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;
            setHeight(h);
        }
        super.showAsDropDown(anchor);
    }

    @Override
    public void showAsDropDown(View anchor, int xoff, int yoff) {
        if(Build.VERSION.SDK_INT >= 24) {
            Rect rect = new Rect();
            anchor.getGlobalVisibleRect(rect);
            int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom;
            setHeight(h);
        }
        super.showAsDropDown(anchor, xoff, yoff);
    }



    //获取权限
    private void initPermissions() {
        apkPath = appOpenBean.getApkUrl();
        boolean isAllGranted = checkPermissionAllGranted(new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE});
        // boolean isAllGranted = checkPermissionAllGranted(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE});
        //判断是否已经赋予权限
        if (isAllGranted) {
            boolean isReade = checkPermissionAllGranted(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,});
            if (isReade) {
                if(!UIUtils.isEmpty(apkPath) && apkPath.length()>4){
                    FileDownloader.setup(mCntext);
                    DownloadInstall(apkPath);
                }
            } else {
                ActivityCompat.requestPermissions((Activity) mCntext, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 50);
            }

        } else {
            //申请权限，字符串数组内是一个或多个要申请的权限，1是申请权限结果的返回参数，在onRequestPermissionsResult可以得知申请结果
            ActivityCompat.requestPermissions((Activity) mCntext, new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 98);
            new ActivityCompat.OnRequestPermissionsResultCallback() {
                @Override
                public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
                    if (requestCode == 98) {
                        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        } else {
                            ToastUtil.show("权限申请失败");
                        }
                    }
                    if(requestCode == 10086){
                        installApk(mCntext,apkFilePath);
                    }
                }
            };


            // ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 98);
        }
    }

    //8.0安装应用权限
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        Uri packageURI = Uri.parse("package:" + packageName);
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        ((Activity)mCntext).startActivityForResult(intent, 10086);
    }
    /**
     * 安装apk
     */
    public void installApk(Context context, String filePath) {
        if (context == null || filePath == null) {
            return;
        }


        File file = new File(filePath);
        if (!file.exists()) return;
        /*********下载完成，点击安装***********/
        Log.d("installApk","installApk2");
        try{
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri apkUri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Log.d("installApk","installApk3");
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                apkUri = FileProvider.getUriForFile(context, packageName+".fileprovider", file);
            } else {
                Log.d("installApk","installApk4");
                apkUri = Uri.fromFile(file);
            }
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            // 查询所有符合 intent 跳转目标应用类型的应用，注意此方法必须放置在 setDataAndType 方法之后
            List<ResolveInfo> resolveLists = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            // 然后全部授权
            for (ResolveInfo resolveInfo : resolveLists){
                String packageName = resolveInfo.activityInfo.packageName;
                context.grantUriPermission(packageName, apkUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
            Log.d("installApk","installApk5");
            context.startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                boolean hasInstallPermission = isHasInstallPermissionWith(context);
                if (!hasInstallPermission) {
                    startInstallPermissionSettingActivity();
                }
            }
        }

    }



    @RequiresApi (api = Build.VERSION_CODES.O)
    private boolean isHasInstallPermissionWith(Context context){
        if (context == null){
            return false;
        }
        return context.getPackageManager().canRequestPackageInstalls();
    }

    /**
     * 检查是否拥有指定的所有权限
     */
    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(mCntext, permission) != PackageManager.PERMISSION_GRANTED) {
                // 只要有一个权限没有被授予, 则直接返回 false
                return false;
            }
        }
        return true;
    }
    /**
     * 系统下载器分配的唯一下载任务id，可以通过这个id查询或者处理下载任务
     */
    private void DownloadInstall(String apkUrl) {
        tv_btn.setText("0%");
        tv_btn.setBackground(mCntext.getResources().getDrawable(R.color.transparent));
        progressBar.setVisibility(View.VISIBLE);
        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator+fileLoad;
        apkFilePath = filePath+apkName+".apk";
        //清除文件
        deleteDir(filePath);
        //下载文件
        FileDownloader.getImpl().create(apkUrl)
                .setPath(apkFilePath)
                .setForceReDownload(true)
                .setListener(new FileDownloadListener() {

                    //等待
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        //    mProgressDialog.setMax(totalBytes);
                        progressBar.setMax(100);
                        tv_btn.setText("0%");

                    }
                    //下载进度回调
                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        if(soFarBytes != 0 &&  totalBytes!=0 ){
                            double p = Double.valueOf(soFarBytes)/ Double.valueOf(totalBytes)*100;
                            if(p>100){
                                p=100;
                            }
                            int num = (new Double(p)).intValue();
//                            BigDecimal b = new BigDecimal(p);
//                            double f1  = b.setScale(0,   BigDecimal.ROUND_HALF_UP).doubleValue();
                            tv_btn.setText(num+"%");

                            progressBar.setProgress(num);

                        }
                    }
                    //完成下载
                    @Override
                    protected void completed(BaseDownloadTask task) {
                        tv_btn.setText( "下载完成");
                        progressBar.setVisibility(View.GONE);
                        installApk(mCntext,apkFilePath);

                    }
                    //暂停
                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        ToastUtil.show("下载暂停");
                    }
                    //下载出错
                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        tv_btn.setText("文件异常，重新下载");
                        progressBar.setVisibility(View.GONE);
                        showDialogDownloadError();
                    }
                    //已存在相同下载
                    @Override
                    protected void warn(BaseDownloadTask task) {

                    }
                }).start();

    }

    private void showDialogDownloadError() {
        final AlertDialog builder = new AlertDialog.Builder(mCntext).create();
        builder.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        builder.show();
        if (builder.getWindow() == null) return;
        builder.setCanceledOnTouchOutside(false);
        builder.getWindow().setContentView(R.layout.download_dialog_pop_alert);//设置弹出框加载的布局

        TextView cancle = (TextView) builder.findViewById(R.id.tv_giveup);

        TextView sure = (TextView) builder.findViewById(R.id.tv_sure);
        builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return true;
            }
        });

        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.dismiss();
                initPermissions();
            }
        });
    }

    /**
     * 删除文件夹
     *
     * @param path
     */
    public static void deleteDir(String path)
    {
        File dir = new File(path);
        deleteDirWihtFile(dir);
    }

    //删除文件及文件夹
    public static void deleteDirWihtFile(File dir) {
        try {
            if (dir == null || !dir.exists() || !dir.isDirectory())
                return;
            for (File file : dir.listFiles()) {
                if (file.isFile())
                    file.delete(); // 删除所有文件
                else if (file.isDirectory())
                    deleteDirWihtFile(file); // 递规的方式删除文件夹
            }
            dir.delete();// 删除目录本身
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}